<template>
  <div>
    <el-dialog
      title="权限配置"
      :visible.sync="roledialogVisible"
      v-loading="diaLoading"
    >
      <el-tree
        :data="systemPermissions"
        show-checkbox
        node-key="id"
        :default-checked-keys="assignedPermissions"
        :props="defaultProps"
        @check="currentChecked"
      >
      </el-tree>
      <div slot="footer">
        <el-button @click="rolecancel">取消</el-button>
        <el-button @click="roleConfirm">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form
        ref="form"
        :model="formData"
        label-width="80px"
        :rules="formRules"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="说明" prop="desc">
          <el-input v-model="formData.desc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button @click="confirm">确定</el-button>
      </div>
    </el-dialog>
    <div class="userList-container">
      <el-form :model="searchFormData" inline class="myForm"> 
        <el-form-item prop="name">
          <el-input
            v-model="searchFormData.name"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getData"
            >查找</el-button
          >
          <el-button @click="openDialog('add', '添加', null)" type="primary"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table
        :data="tableData"
        border
        v-loading="tableloading"
        class="myTab"
      >
        <el-table-column
          align="center"
          label="角色名称"
          prop="name"
          sortable
    
        ></el-table-column>
        <el-table-column
          align="center"
          label="说明"
          prop="desc"
         
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="openDialog('edit', '编辑', scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" @click="deleteRow(scope.row)"
              >删除</el-button
            >
            <el-button type="primary" @click="openRoleDia(scope.row)"
              >授权</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.pageInfo.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="this.pageInfo.limit"
        background
        layout="total,sizes, prev, pager, next,jumper"
        :total="this.pageInfo.total"
        class="myStyle"
      >
      </el-pagination>
    </div>
  </div>
</template>
  
<script>
import axios from "axios";
export default {
  name: "roleManage",
  componentTitle: "角色管理",
  data() {
    return {
      systemPermissions: [],

      myPermissions: {
        roleId: "",
        permissions: [],
      },

      assignedPermissions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      roledialogVisible: false,
      token: sessionStorage.getItem("Shopping-Admin-Token"),
      dialogVisible: false,
      searchFormData: {
        page: 1,
        limit: 20,
        name: "",
        userId: "",
      },
      tableData: [],
      formRules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "change" },
        ],
      },
      formData: {
        roleIds: [],
      },
      pageInfo: {
        page: 1,
        limit: 10,
        total: 0,
      },
      tableloading: false,
      diaLoading: false,
      dialogType: "",
      dialogTitle: "",
      adminStatus: [
        { label: "超级管理员", value: 1 },
        { label: "商场管理员", value: 2 },
        { label: "推广管理员", value: 3 },
      ],
    };
  },
  mounted() {
    this.getData();
  },
  filters: {
    tableFilter(value, options) {
      let index = options.findIndex((item) => {
        return Number(item.value) === Number(value);
      });
      if (index < 0) {
        return "---";
      } else {
        return options[index].label;
      }
    },
  },
  methods: {
    currentChecked(nodeObj, SelectedObj) {
      
      var reg = /[\u4e00-\u9fa5]/g;
      var key = SelectedObj.checkedKeys.toString();
      key = key.replace(/[ ]/g, ""); //去空格
      key = key.replace(reg, ""); //去除中文
      var newArr = key.split(",");
      this.myPermissions.permissions = newArr.filter((item) => item);

    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([{ name: "region" }]);
      }
      if (node.level > 1) return resolve([]);

      setTimeout(() => {
        const data = [
          {
            name: "leaf",
            leaf: true,
          },
          {
            name: "zone",
          },
        ];

        resolve(data);
      }, 500);
    },
    avatarSuccess(res, file) {
      //
      this.formData.avatar = res.data.url.replace(
        /localhost:8888/g,
        "192.168.200.251:8888"
      );
      // this.dialogFormData.picUrl = res.data.url.replace(/localhost:8888/g, '192.168.200.251:8888')
    },
    cancel() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    rolecancel() {
      this.roledialogVisible = false;
    },
    roleConfirm() {
      axios({
        url: "http://192.168.200.251:8888/admin/role/permissions",
        method: "post",
        data: {
          ...this.myPermissions,
        },
        headers: {
          "Content-Type": "application/json; charset=utf-8",
          "Shopping-Admin-Token": sessionStorage.getItem(
            "Shopping-Admin-Token"
          ),
        },
      }).then((res) => {
        console.log(res);
        if (res.data.errno === 0) {
          this.rolecancel();
          this.$notify.success({ title: "授权成功" });
        } else {
          this.$notify.error({ title: "授权失败" });
        }
      });
    },
    addData() {
      axios({
        url: "http://192.168.200.251:8888/admin/role/create",
        method: "post",
        data: {
          ...this.formData,
        },
        headers: {
          "Content-Type": "application/json; charset=utf-8",
          "Shopping-Admin-Token": sessionStorage.getItem(
            "Shopping-Admin-Token"
          ),
        },
      }).then((res) => {
        console.log("test", 123);
        if (res.data.errno === 0) {
          this.cancel();
          this.$notify.success({ title: "添加成功" });

          this.getData();
        } else {
          this.$notify.error({ title: "添加失败" });
        }
      });
    },
    editData() {
      axios({
        url: "http://192.168.200.251:8888/admin/role/update",
        method: "post",
        data: {
          ...this.formData,
        },
        headers: {
          "Shopping-Admin-Token": sessionStorage.getItem(
            "Shopping-Admin-Token"
          ),
        },
      }).then((res) => {
        if (res.data.errno === 0) {
          this.cancel();
          this.$notify.success({ title: "编辑成功" });
          this.getData();
        } else {
          this.$notify.error({ title: "编辑失败" });
        }
      });
    },

    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.dialogType === "add") {
            this.addData();
          } else if (this.dialogType === "edit") {
            this.editData();
          }
        } else {
          return false;
        }
      });
    },
    openDialog(type, title, row) {
      this.dialogVisible = true;
      this.dialogType = type;
      this.dialogTitle = title;
      if (type === "edit") {
        this.$nextTick(() => {
          this.formData = Object.assign({}, row);
        });
      }
    },
    openRoleDia(row) {
      console.log(row);
      this.diaLoading = true;
      this.roledialogVisible = true;
      this.roleUpdata(row);
      this.myPermissions.roleId = row.id;
    },
    roleUpdata(row) {
      console.log("sssssss", row.id);
      axios({
        url: "http://192.168.200.251:8888/admin/role/permissions",
        method: "get",
        params: {
          roleId: row.id,
        },
        headers: {
          "Content-Type": "application/json; charset=utf-8",
          "Shopping-Admin-Token": sessionStorage.getItem(
            "Shopping-Admin-Token"
          ),
        },
      }).then((res) => {
        console.log("获取角色列表", res.data.data.assignedPermissions);
        this.systemPermissions = res.data.data.systemPermissions;
        this.assignedPermissions = res.data.data.assignedPermissions;
        this.diaLoading = false;
      });
    },
    deleteRow(row) {
      this.$confirm("确定删除该条数据吗").then(() => {
        axios({
          url: "http://192.168.200.251:8888/admin/role/delete",
          method: "post",
          data: {
            id: row.id,
          },
          headers: {
            "Content-Type": "application/json; charset=utf-8",
            "Shopping-Admin-Token": sessionStorage.getItem(
              "Shopping-Admin-Token"
            ),
          },
        }).then((res) => {
          console.log("删除", res);
          this.getData();
        });
      });
    },

    getData() {
      (this.tableloading = true),
        axios({
          url: "http://192.168.200.251:8888/admin/role/list",
          method: "get",
          params: {
            page: this.pageInfo.page,
            limit: this.pageInfo.limit,
            ...this.searchFormData,
          },
          headers: {
            "Content-Type": "application/json; charset=utf-8",
            "Shopping-Admin-Token": sessionStorage.getItem(
              "Shopping-Admin-Token"
            ),
          },
        }).then((res) => {
          console.log("获取用户列表", res);
          (this.tableData = res.data.data.list),
            (this.pageInfo.total = res.data.data.total);
          this.tableloading = false;
        });
    },
    handleCurrentChange(value) {
      console.log("当前页码", value);
      this.pageInfo.page = value;
      this.getData();
    },
    handleSizeChange(value) {
      console.log("当前每页多少条", value);
      this.pageInfo.limit = value;
      this.getData();
    },
  },
};
</script>
<style lang="scss" scoped>
.userList-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.myForm{
display: flex;
justify-content: flex-end; 
margin-top: 30px;
margin-right: 22px;
}

.myTab{
  width: 95%;
  text-align: center;
  margin: 0 auto;
}

.myDal{
  .input1{
    width:340px; 
    margin-left: 40px;
  }
}
.myStyle{
  margin-top: 70px;
  margin-left: 80px;
}
</style>








    
